package io.nutz.nutzsite.common.quartz.job;

import io.nutz.nutzsite.module.sys.models.User;
import io.nutz.nutzsite.module.sys.services.UserService;

import java.util.List;

import org.apache.shiro.session.Session;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;


/**
 * @author apple
 */
//@Scheduled(cron="*/5 * * * * ?")
@IocBean//(args = {"refer:dao"})
public class TestJob implements Job {

    private static final Log log = Logs.get();

    @Inject("refer:shiroWebSessionManager")
    private DefaultWebSessionManager webSessionManager;

    @Inject
    private UserService userService;

/**
 * 校验后，过期的session将被WebSessionListener立即清理
 */
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
    	webSessionManager.validateSessions();
    	updateSessions();
    }
    public void updateSessions()
    {
    	List<User> listuserol=userService.query(Cnd.where("userOnline","=",true));
    	for (User userOnline : listuserol) {
    		String sessionId=userOnline.getSessionId();
    		//String uid=userOnline.getId();
    		//log.debug("\r\nuser:"+sessionId+"-"+uid+" exist...\r\n");
    		try{
				if (sessionId == null || sessionId.length() == 0) return;
				//session无效时，read报Exception
				//Session oldSession = 
						webSessionManager.getSessionDAO().readSession(sessionId);
				//if (oldSession != null) {
					// log.debug("\r\noldsession:"+sessionId+"-"+uid+" exist...\r\n");
				//}
    		}catch(Exception e){
    			//userService.deleteOnlineById(sessionId);
    			//userService.update(Chain.make("userOnline", false).add("sessionId", ""), Cnd.where("id", "=", uid));
    			log.debug("\r\n"+e.getMessage()+"\r\n");
    		}
		} 
    }
}
